package cn.datawin.cmppprovider.init;

import cn.datawin.cmppprovider.handler.cmpp.CmppServerCustomHandler;
import com.alibaba.fastjson.JSONObject;
import com.drondea.sms.channel.ChannelSession;
import com.drondea.sms.common.SequenceNumber;
import com.drondea.sms.common.util.CommonUtil;
import com.drondea.sms.conf.cmpp.CmppServerSocketConfig;
import com.drondea.sms.message.IMessage;
import com.drondea.sms.message.MessageProvider;
import com.drondea.sms.message.cmpp.CmppDeliverRequestMessage;
import com.drondea.sms.session.cmpp.CmppServerSessionManager;
import com.drondea.sms.thirdparty.SmsAlphabet;
import com.drondea.sms.thirdparty.SmsDcs;
import com.drondea.sms.type.CmppConstants;
import com.drondea.sms.type.IMessageResponseHandler;
import com.drondea.sms.type.UserChannelConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Order(1)
@Slf4j
public class CmppServerInit implements CommandLineRunner {

    public static AtomicInteger sum = new AtomicInteger();
    public static ConcurrentLinkedQueue<JSONObject> inboxQueue = new ConcurrentLinkedQueue<>();

    @Value("${cmpp.port}")
    public Integer cmppPort;

    @Override
    public void run(String... args) throws Exception {

        CmppServerSocketConfig socketConfig = new CmppServerSocketConfig("syy", cmppPort);
        CmppServerCustomHandler customHandler = new CmppServerCustomHandler();
        socketConfig.setVersion(CmppConstants.VERSION_20);
        CmppServerSessionManager sessionManager = new CmppServerSessionManager(name -> {

            if (name.startsWith("2371")) {
                UserChannelConfig userChannelConfig = new UserChannelConfig();
                userChannelConfig.setUserName(name);
                userChannelConfig.setId(name);
                userChannelConfig.setPassword("SvKr6w");
                userChannelConfig.setChannelLimit(15);
                userChannelConfig.setQpsLimit(6000);
                return userChannelConfig;
            }
            return null;
        }, socketConfig, customHandler);

        //设置消息提供者（从数据库或者缓存获取消息即可），这里获取的消息是回执或者上行短信
        sessionManager.setMessageProvider(new MessageProvider() {
            @Override
            public List<IMessage> getTcpMessages(ChannelSession channelSession) {
                JSONObject jsonObject = inboxQueue.poll();
                if (jsonObject == null) {
                    return null;
                }

                CmppDeliverRequestMessage mo = new CmppDeliverRequestMessage();
                SequenceNumber sequenceNumber = channelSession.getSequenceNumber();
                mo.getHeader().setSequenceId(sequenceNumber.next());
                mo.setRegisteredDelivery((short) 0);
                mo.setMsgContent(jsonObject.getString("content"));
                mo.setSrcTerminalId(jsonObject.getString("phone"));
                //收到响应的回调
                mo.setMessageResponseHandler(new IMessageResponseHandler() {
                    @Override
                    public void messageComplete(IMessage request, IMessage response) {
                    }

                    @Override
                    public void messageExpired(String key, IMessage request) {
                    }

                    @Override
                    public void sendMessageFailed(IMessage request) {
                    }
                });
                mo.setMsgFmt(SmsDcs.getGeneralDataCodingDcs(SmsAlphabet.RESERVED));
                return CommonUtil.getLongMsgSlices(mo, channelSession.getConfiguration(), sequenceNumber);
            }

            @Override
            public void responseMessageMatchFailed(String requestKey, IMessage response) {

            }
        });

        sessionManager.doOpen();

        log.info("cmpp服务器监听已经启动");
    }
}
